package com.qzxl.conntext;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.healthmarketscience.jackcess.DatabaseBuilder;
import com.healthmarketscience.jackcess.Row;
import com.healthmarketscience.jackcess.Table;
import com.qzxl.conntext.listener.AccessListener;
import com.qzxl.conntext.producer.AccessProducer;
import com.qzxl.conntext.utils.NoGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

@Configuration
@EnableScheduling
public class InitParsingAccess_ {

    public static Map<Object, Object> fileMap = new ConcurrentHashMap<>(); // 保存已经执行的mbd文件+处理时间

    public static List<String> experimentNumberList = new CopyOnWriteArrayList<>(); //保存已经执行设备的编号

    public final Map<String, String> propertiesMap = ReadConfig.read(); // 读取配置文件的属性

    private static final Logger logger = LoggerFactory.getLogger(InitParsingAccess_.class);

    public InitParsingAccess_(KafkaTemplate<String, String> kafkaTemplate) {
        this.kafkaTemplate = kafkaTemplate;
    }

    private final KafkaTemplate<String, String> kafkaTemplate;

    @Value("${myAddress.path}")
    private String path; // 路径

    @Value("${myAddress.DEVICETYPE}")
    private String DEVICETYPE; // 设备名称


    @Scheduled(cron = "0 0 0/1 * * ?")
    @PostConstruct
    @Scheduled(fixedRate=10000)
    public void AccessParing() {
        logger.info("准备开始遍历目录文件");
        File file = new File(path);
        File[] files = file.listFiles();
        if (files == null) {
            logger.info("文件名不存在");
        } else {
            for (File f : files) {
                if (!fileMap.containsKey(f.getName())) {
                    fileMap.put(f.getName(),new Date());
                    logger.info("-----------------------现在读取的文件名是:" + f.getName());
                    try {
                        Table table =
                                DatabaseBuilder.open(new File(path + "\\" + f.getName())).getTable("record");
                        for (Row row : table) {
                            String no = (String)row.get("型号");
                            //按照规范替换字符，可查阅资料的规范
                            no = no.replaceAll("/","-");
                            no = no.replaceAll("-","_");
                            logger.info("------------------------------------型号是="+no);
                            if (!experimentNumberList.contains(no)) {
                                logger.info("----------------------准备注册---------------------------------");
                                register(row); // 准备注册
                            } else {
                                logger.info("--------------------------------准备上报-------------------------------");
                                report(row); // 已经被注册过，直接上报
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error("-------------------------错误消息是" + e);
                    }
                }
            }
        }
    }

    public void register(Row row) {
        String esn = createID();
        try {
            String deviceName = (String) row.get("型号");
            deviceName = deviceName.replaceAll("/","-");
            deviceName = deviceName.replaceAll("-","_");
            String deviceTitle = deviceName+"实验数据";
            new AccessProducer().register(esn, DEVICETYPE, deviceName,deviceTitle, kafkaTemplate);
            report(row);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("----------------------错误信息是" + e);
        }
    }

    public void report(Row row) {
        JSONObject jsonObject = new JSONObject();
        for (Map.Entry<String, String> entry : propertiesMap.entrySet()) {
            jsonObject.put(entry.getKey(), row.get(entry.getValue()));
        }
        logger.info("--------------------------------从配置文件读取后的jsonObject="+jsonObject);
        try{
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(jsonObject);
            JSONObject Json = new JSONObject();
            JSONObject RequestJson = new JSONObject();
            Json.put("id", NoGenerator.getUUID());
            Json.put("requestTime", String.valueOf(NoGenerator.getDate()));
            String deviceName = (String) row.get("型号");
            deviceName = deviceName.replaceAll("/","-");
            deviceName = deviceName.replaceAll("-","_");
            logger.info("******************************deviceId="+AccessListener.deviceName.get(deviceName));
            Json.put("deviceId", AccessListener.deviceName.get(deviceName));
            Json.put("modelName",DEVICETYPE);
            RequestJson.put("serviceProperties", jsonArray);
            Json.put("request", RequestJson);
            logger.info("-------------------------------上报的数据是="+Json);
            kafkaTemplate.send(
                    "sys." + DEVICETYPE + ".thing.serviceid.property.post", DEVICETYPE, Json.toJSONString());
            String s = jsonObject.get("empiricalName").toString().replaceAll("/","-");
            s = s.replaceAll("-","_");
            experimentNumberList.add(s);
            logger.info("设备类型=" + DEVICETYPE);
            logger.info("----------------数据上报-----------------------------------");
        }catch (Exception e){
            logger.error("-----------------------------错误信息是"+e);
        }
    }

    // 位数，默认是8位
    private static final long w = 100000000;

    public static String createID() {
        long r = (long) ((Math.random() + 1) * w);
        return System.currentTimeMillis() + String.valueOf(r).substring(1);
    }
}
